package com.xrtn.controller;

import com.xrtn.bean.*;
import com.xrtn.mapper.*;
import com.xrtn.service.ICommonService;
import com.xrtn.service.TestService;
import com.xrtn.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * Created by tu_pei on 2018/2/5.
 */
@Api("测试")
@Controller
@RequestMapping("/test")
//http://192.1.1.1:8080/xrtn-manager/test/index
public class TestController {

    @Autowired
    private TestService testService;

    @Autowired
    private ICommonService commonService;

    @Autowired
    private TDoctorMonthRelMapper doctorMonthRelMapper;

    @Autowired
    private InitGradeDoctorMapper gradeDoctorMapper;

    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;

    @Autowired
    private TOrderInfoMapper orderInfoMapper;

    @Autowired
    private TReplyInfoMapper replyInfoMapper;

    @Autowired
    private TUserTreatmentRelMapper treatmentRelMapper;

    @Autowired
    private TPatientTreatmentMapper patientTreatmentMapper;

    @ApiOperation(value = "处理同一预约对应多个病历的情况", notes = "处理同一预约对应多个病历的情况")
    @RequestMapping(value = "/selectSameBookingTreatmentList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectSameBookingTreatmentList() {

        ResponseData data = new ResponseData();

        List<Map<String,Object>> sameBookTreat = patientTreatmentMapper.selectSameBookingTreatmentList();
        for (Map<String,Object> sbt : sameBookTreat) {
            Map<String, Object> params = new HashMap<>();
            Integer booking_id = (Integer)sbt.get("booking_id");
            if (booking_id != null && booking_id > 0) {
                params.put("bookingId", booking_id);
                List<TPatientTreatment> treatList = patientTreatmentMapper.selectByBookingId(params);
                if (treatList.size() == 2) {
                    for (TPatientTreatment treatment : treatList) {
                        Integer state = treatment.getTreatmentState();
                        if (state == 0) {
                            TPatientTreatment record = new TPatientTreatment();
                            record.setTreatmentId(treatment.getTreatmentId());
                            record.setTreatmentState(1);
                            patientTreatmentMapper.updateByPrimaryKeySelective(record);
                        }
                        if (state == 1) {
                            patientTreatmentMapper.deleteByPrimaryKey(treatment.getTreatmentId());
                        }
                    }
                }
            }
        }

        return data;
    }

    @ApiOperation(value = "核算符合升级标准", notes = "核算连续三个月连续符合升级标准")
    @RequestMapping(value = "/selectDoctorUpwardJob", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectDoctorUpwardJob() {

        ResponseData date = new ResponseData();
//
//        Map<String, Object> params = new HashMap<>();
//        params.put("userStatus", 0);// 0 在职 ， 1 离职 2辞退
//        List<SysUserInfo> userList = sysUserInfoMapper.selectUserListByMap(params);
//
//        for (SysUserInfo userInfo : userList) {
//
//            Integer userLevel = userInfo.getUserLevel();
//            //当用户等级为1级，
//            if (userLevel == 1) {
//                params = new HashMap<>();
//                params.put("year", new Date());
//                params.put("doctorId", userInfo.getUserId());
//                List<TDoctorMonthRel> doctorMonthList = doctorMonthRelMapper.selectUserMonthSale(params);
//                Integer count = 0;
//                for (TDoctorMonthRel monthRel : doctorMonthList) {
//                    //任意三个月达到向上一级标准晋升一级
//                    if (monthRel.getUserLevel() == (userInfo.getUserLevel()+1) ) {
//                        count++;
//                    }
//                    if (count == 3) {
//                        //用户升级成功
//                        if( userInfo.getUserLevel()  < 5 ){
//                            userInfo.setUserLevel(userInfo.getUserLevel() + 1);
//                            sysUserInfoMapper.updateByPrimaryKeySelective(userInfo);
//                        }
//                    }
//                }
//            } else {
//                //连续3个月内
//                params = new HashMap<>();
//                params.put("month", 3);
//                params.put("doctorId", userInfo.getUserId());
//                List<TDoctorMonthRel> doctorMonthList = doctorMonthRelMapper.selectUserMonthSale(params);
//                if (doctorMonthList.size() == 3) {
//                    Integer count = 0;
//                    for (TDoctorMonthRel monthRel : doctorMonthList) {
//                        if (monthRel.getUserLevel() == (userInfo.getUserLevel()+1) ) {
//                            count++;
//                        }
//                    }
//                    //连续三个月  订单|满意度|月治愈率都达标修改用户等级
//                    if( count == 3){
//                        //用户升级成功
//                        if( userInfo.getUserLevel() < 5 ){
//                            userInfo.setUserLevel(userInfo.getUserLevel() + 1);
//                            sysUserInfoMapper.updateByPrimaryKeySelective(userInfo);
//                        }
//                    }
//                }
//            }
//        }
        return date;
    }
    @ApiOperation(value = "每月月末核算本月 订单数、 满意度 、 月治愈率 核算本月业绩等级", notes = "每月月末核算本月 订单数、 满意度 、 月治愈率 核算本月业绩等级")
    @RequestMapping(value = "/selectDoctorMonthSaleJob", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectDoctorMonthSaleJob() {

        ResponseData date = new ResponseData();

//        Map<String,Object> params = new HashMap<>();
//        params.put("userStatus", 0);// 0 在职 ， 1 离职 2辞退
//
//        List<SysUserInfo> userList = sysUserInfoMapper.selectUserListByMap(params);
//
//        Integer orderCount = 0, replyRatio = 0;
//
//        BigDecimal treatmentRaion = new BigDecimal(0);
//
//        for (SysUserInfo userInfo : userList){
//            //最高等级为 5级
//            Integer gradeNumber = userInfo.getUserLevel();
//            if(userInfo.getUserLevel() < 5 ){
//                gradeNumber = userInfo.getUserLevel()+ 1;
//            }
//            params.put("gradeNumber", gradeNumber );
//            InitGradeDoctor gradeDoctor = gradeDoctorMapper.selectByMap(params);
//
//            TDoctorMonthRel monthRel = new TDoctorMonthRel();
//
//            //当月订单数
//            orderCount = orderInfoMapper.selectDoctorOrderCount(userInfo.getUserId());
//            //月满意度比率
//            replyRatio = replyInfoMapper.selectUserReplyRatio(userInfo.getUserId());
//
//            //月治愈率
//            treatmentRaion = treatmentRelMapper.selectTreatmentMonth(userInfo.getUserId());
//
//            monthRel.setMonthStr(DateUtils.format(new Date(),"yyyy-MM"));
//            //治愈率
//            monthRel.setMonthTreatmentRatio(treatmentRaion);
//            //医生
//            monthRel.setDoctorId(userInfo.getUserId());
//            //订单数
//            monthRel.setOrderNumber(orderCount);
//            //满意度
//            monthRel.setReplyRatio(new BigDecimal(replyRatio));
//            //投诉率
//            monthRel.setComplainRatio(new BigDecimal(0));
//
//            monthRel.setCreateTime(new Date());
//
//            System.out.println("monthRel = " + JSONObject.fromObject(monthRel).toString());
//
//            monthRel.setUserLevel(userInfo.getUserLevel());
//
//            if( monthRel.getOrderNumber() >= gradeDoctor.getGradeStartScore() &&
//                monthRel.getReplyRatio().intValue() >= gradeDoctor.getReplyRatio() &&
//                monthRel.getMonthTreatmentRatio().intValue() >= gradeDoctor.getMonthTreatmentRatio()){
//                if(userInfo.getUserLevel() < 5 ){
//                    //本月达到上一级别标准
//                    monthRel.setUserLevel(userInfo.getUserLevel() + 1);
//                }
//            }
//            doctorMonthRelMapper.insertSelective(monthRel);
//        }
        return date;
    }

    @ApiOperation(value = "处理同一预约对应多个病历的情况", notes = "处理同一预约对应多个病历的情况")
    @RequestMapping(value = "/testTreatmentJob", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData testTreatmentJob() {
        ResponseData data = new ResponseData();
        Map<String,Object> params = new HashMap<>();
        params.put("passHours", 24);
        List<TPatientTreatment> treatmentList = commonService.selectOverTreatment(params);
        for (TPatientTreatment treatment : treatmentList){
            treatment.setTreatmentState(2); // 已失效
            commonService.updateTreatment(treatment);
        }
        return data;
    }

    public static void main(String args[]) throws ParseException {

//        String url = "http://person.sac.net.cn/pages/registration/train-line-register!orderSearch.action";
//        String paramsStr = "filter_EQS_OTC_ID=10&ORDERNAME=AOI#AOI_NAME&ORDER=ASC&sqlkey=registration&sqlval=SELECT_LINE_PERSON";

        Map<String,String> params = new HashMap<>();
//        params.put("filter_EQS_OTC_ID", "10");
//        params.put("ORDERNAME", "AOI#AOI_NAME");
//        params.put("ORDER", "ASC");
//        params.put("sqlkey", "registration");
//        params.put("sqlval", "SELECT_LINE_PERSON");
//
//        System.out.println(HttpUtils.submitPostData(url,params,"utf-8"));
//
//        url = "http://person.sac.net.cn/pages/registration/train-line-register!gsUDDIsearch.action";
//        params = new HashMap<>();
//        params.put("filter_EQS_AOI_ID", "1999110");
//        params.put("filter_GTS_RNUM", "0");
//        params.put("filter_LES_ROWNUM", "100");
//        params.put("filter_EQS_PTI_ID", "");
//        params.put("ORDERNAME", "PP#PTI_ID,PP#PPP_NAME");
//        params.put("ORDER", "ASC");
//        params.put("sqlkey", "registration");
//        params.put("sqlval", "SEARCH_FINISH_OTHER_PUBLICITY");
//
//        System.out.println(HttpUtils.submitPostData(url,params,"utf-8"));

//        url = "http://person.sac.net.cn/pages/registration/train-line-register!gsUDDIsearch.action";
//        params = new HashMap<>();
//        params.put("filter_LES_ROWNUM", "6A605D225103D87BE053D651A8C07543");
//        params.put("filter_EQS_AOI_ID", "1999110");
//        params.put("filter_GTS_RNUM", "0");
//        params.put("filter_LES_ROWNUM", "100");
//        params.put("filter_EQS_PTI_ID", "");
//        params.put("ORDERNAME", "PP#PTI_ID,PP#PPP_NAME");
//        params.put("ORDER", "ASC");
//        params.put("sqlkey", "registration");
//        params.put("sqlval", "SEARCH_FINISH_PUBLICITY");

//        url = "http://person.sac.net.cn/pages/registration/train-line-register!gsUDDIsearch.action";
//        params = new HashMap<>();
//        params.put("filter_EQS_PPP_ID", "6A605D225103D87BE053D651A8C07543");
//        params.put("sqlkey", "registration");
//        params.put("sqlval", "SD_A02Leiirkmuexe_b9ID");
//
//        String RPI_ID = JSONArray.fromObject(HttpUtils.submitPostData(url,params,"utf-8")).getJSONObject(0).optString("RPI_ID");
//
//        url = "http://person.sac.net.cn/pages/registration/train-line-register!gsUDDIsearch.action";
//        params = new HashMap<>();
//        params.put("filter_EQS_RPI_ID", RPI_ID);
//        params.put("sqlkey", "registration");
//        params.put("sqlval", "SELECT_PERSON_INFO");

//        url = "http://amazon.malllib.com/amazon/home/get_bsrranksales.jhtml";
//        params = new HashMap<>();
//        params.put("rank", "2");
//        params.put("categoryid", "30");
//        params.put("country", "1");
//        System.out.println(HttpUtils.submitPostData(url,params,"utf-8"));


//        if( new Date().getTime() > DateUtils.parse(DateUtils.addDay(new Date(),1),DateUtils.YYYY_MM_DD).getTime()){
//            System.out.println("123");
//        }




    }
    public static void remove(List<String> list, String target) {
        for (int i = list.size() - 1; i >= 0; i--) {
            String item = list.get(i);
            if (target.equals(item)) {
                list.remove(item);
            }
        }
    }

    // 获取短链接平台token，一年执行一次
    public static void getDwzToken() {
        Map<String,String> map = new TreeMap<String, String>();
        map.put("api_key","8A123B173C2759248823D11996CC534F");

        String codeObj = HttpUtils.sendPost("https://dwz3.cn/apis/authorize/getCode","");
        String codes = JSONObject.fromObject(codeObj).optString("data");
        if(ObjUtils.isNotEmpty(codes)){
            map.put("code", codes);
            map.put("request_time",String.valueOf(System.currentTimeMillis() / 1000));
            String signStr = "";
            for (String key : map.keySet()) {
                String value = map.get(key);
                signStr += key + "=" + value;
            }
            System.out.println("signStr: " + signStr + "qoPnutmWOoDOoGLSgvfDJOKAxGFUgRIN");
            String sign = MD5Utils.md5Password(signStr + "qoPnutmWOoDOoGLSgvfDJOKAxGFUgRIN");
            map.put("sign", sign);
            String str = HttpUtils.submitPostData("https://dwz3.cn/apis/authorize/getAccessToken",map,"utf-8");
            System.out.println("str = "+str);
        }
    }
}
